
package com.wyzz.hr.action;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.bo.IClientBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.IRecruitapplierBo;
import com.wyzz.hr.bo.ISysLogBO;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Recruitapplier;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.SysConfigManager;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

public class EditEmp extends BaseAction {

	public EditEmp() {
		dbConfigManager = DatabaseSysConfigManager.getInstance();
	}

	public String createEmp() throws Exception {
		if (!validateId())
			return "input";
		if (!validateMQW())
			return "input";
		if (emp.getPosition() == null
				|| StringUtils.isEmpty(emp.getPosition().getId())) {
			addErrorInfo("\u8BF7\u9009\u62E9\u8BE5\u5458\u5DE5\u7684\u804C\u4F4D\uFF01");
			return "input";
		}
		String fileName = upload(emp.getEmpDistinctNo());
		if (file != null && fileName.lastIndexOf(".") == -1)
			return "input";
		if (fileName != null && fileName.length() > 0)
			emp.setEmpImage(fileName);
		emp.setEmpStatus(Integer.valueOf(1));
		if (connectionType.equals("0"))
			empMsn = connectionNo;
		else if (connectionType.equals("1"))
			empMsn = (new StringBuilder()).append("QQ:").append(connectionNo)
					.toString();
		else if (connectionType.equals("2"))
			empMsn = (new StringBuilder()).append("WW:").append(connectionNo)
					.toString();
		emp.setEmpMsn(empMsn);
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		String info = empBo.saveCreateEmp(emp, getCurrentEmp(), createUser);
		if (!"SUCC".equals(info)) {
			addErrorInfo(info);
			return "input";
		}
		getSession().setAttribute("curr_oper_no", emp.getId());
		setEmpNo(emp.getId());
		emp.setEmpName(URLEncoder.encode(emp.getEmpName(), "utf-8"));
		addSuccessInfo("\u6DFB\u52A0\u5458\u5DE5\u57FA\u672C\u8D44\u6599\u6210\u529F\u3002");
		if (!StringUtils.isEmpty(applierId)) {
			IRecruitapplierBo applierBo = (IRecruitapplierBo) getBean("applierBo");
			Recruitapplier applier = applierBo.loadApplierById(applierId);
			List saveList = new ArrayList();
			if (applier != null) {
				applier.setRecaRelationEmpNo(new Employee(emp.getId()));
				saveList.add(applier);
				applierBo.saveOrUpdateApplier(saveList);
			}
		}
		return "success";
	}

	public String updateEmp() throws Exception {
		if (!validateId())
			return "input";
		if (!validateMQW())
			return "input";
		if (emp.getPosition() == null
				|| StringUtils.isEmpty(emp.getPosition().getId())) {
			addErrorInfo("\u8BF7\u9009\u62E9\u8BE5\u5458\u5DE5\u7684\u804C\u4F4D\uFF01");
			return "input";
		}
		empTypes = getDrillDown("EmpType", new String[0]);
		locations = getDrillDown("Location", new String[0]);
		benefitTypes = getDrillDown("BenefitType", new String[0]);
		exShiftEnable = dbConfigManager.getProperty("sys.examin.shift.enable")
				.trim();
		if (super.authorityCondition != null
				&& super.authorityCondition.equalsIgnoreCase("OWN")
				&& !getCurrentEmpNo().equalsIgnoreCase(emp.getId())) {
			addErrorInfo("\u60A8\u65E0\u6743\u5BF9\u5176\u4ED6\u5458\u5DE5\u8D44\u6599\u8FDB\u884C\u4FEE\u6539\u64CD\u4F5C!");
			return "general";
		}
		String fileName = upload(emp.getEmpDistinctNo());
		if (file != null && fileName.lastIndexOf(".") == -1)
			return "input";
		String tempImageName = null;
		if (fileName != null && fileName.length() > 0)
			emp.setEmpImage(fileName);
		else if (StringUtils.isNotEmpty(emp.getEmpImage())) {
			tempImageName = emp.getEmpImage();
			emp.setEmpImage((new StringBuilder())
					.append(emp.getEmpDistinctNo()).append(
							emp.getEmpImage().substring(
									emp.getEmpImage().lastIndexOf("."),
									emp.getEmpImage().length())).toString());
		}
		if (connectionType.equals("0"))
			empMsn = connectionNo;
		else if (connectionType.equals("1"))
			empMsn = (new StringBuilder()).append("QQ:").append(connectionNo)
					.toString();
		else if (connectionType.equals("2"))
			empMsn = (new StringBuilder()).append("WW:").append(connectionNo)
					.toString();
		emp.setEmpMsn(empMsn);
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		List errors = empBo.updateEmpByempInfo(emp, getCurrentEmpNo());
		ISysLogBO logBO = (ISysLogBO) SpringBeanFactory.getBean("logBO");
		emp.setLogs(logBO.getLogs("employee", emp.getId()));
		if (errors != null && errors.size() > 0) {
			addErrorInfo(errors);
		} else {
			if (StringUtils.isNotEmpty(emp.getEmpImage())
					&& !emp.getEmpDistinctNo().equalsIgnoreCase(
							oldEmpDistinctNo))
				renameFile(tempImageName != null ? tempImageName : emp
						.getEmpImage(), emp.getEmpDistinctNo());
			addSuccessInfo("\u4FEE\u6539\u5458\u5DE5\u57FA\u672C\u8D44\u6599\u6210\u529F\u3002");
		}
		if (super.authorityCondition.equalsIgnoreCase("ADM"))
			return "success";
		else
			return "general";
	}

	private boolean validateId() {
		if (emp.getEmpIdentificationType().intValue() == 0) {
			String pattern15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
			String pattern18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}(\\d{1}|[xX])$";
			if (!Pattern.matches(pattern15, emp.getEmpIdentificationNo())
					&& !Pattern
							.matches(pattern18, emp.getEmpIdentificationNo())) {
				addFieldError("emp.empIdentificationNo",
						"\u683C\u5F0F\u9519\u8BEF\uFF01");
				return false;
			}
		}
		return true;
	}

	private boolean validateMQW() {
		if (connectionNo.length() == 0)
			return true;
		if (connectionType.equals("0")) {
			String pattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*";
			if (!Pattern.matches(pattern, connectionNo)) {
				addFieldError("connectionNo", "\u683C\u5F0F\u9519\u8BEF\uFF01");
				return false;
			}
		} else if (connectionType.equals("1") && !isNumeric(connectionNo)) {
			addFieldError("connectionNo", "\u6570\u5B57\u9879\uFF01");
			return false;
		}
		return true;
	}

	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		return isNum.matches();
	}

	public String upload(String empNo) throws Exception {
		String fileName = "";
		if (null != file && null != empNo && empNo.trim().length() > 0) {
			String type = fileFileName.substring(fileFileName.lastIndexOf("."));
			fileName = (new StringBuilder()).append(empNo).append(type)
					.toString();
			String message = FileOperate.buildFile(file, "sys.user.image.path",
					"sys.user.image.type", "sys.user.image.length",
					new String[] { fileName, emp.getEmpImage() });
			if (!"success".equals(message)) {
				if ("error".equals(message))
					addFieldError("file",
							"\u6587\u4EF6\u64CD\u4F5C\u9519\u8BEF\uFF01");
				else if ("fileExtendNameError".equals(message))
					addFieldError("file",
							"\u56FE\u7247\u7C7B\u578B\u4E0D\u5339\u914D\uFF01");
				else if ("fileTooLength".equals(message))
					addFieldError("file", "\u56FE\u7247\u8FC7\u5927\uFF01");
				else if ("property".equals(message))
					addFieldError("file",
							"\u5C5E\u6027\u6587\u4EF6\u914D\u7F6E\u9519\u8BEF\uFF01");
				return message;
			}
		}
		return fileName;
	}

	private void renameFile(String oldFileName, String newFileName) {
		String filePath = (new StringBuilder()).append(
				FileOperate.getFileHomePath()).append(
				PropertiesFileConfigManager.getInstance().getProperty(
						"sys.user.image.path")).toString();
		File oldFile = new File((new StringBuilder()).append(filePath).append(
				oldFileName).toString());
		if (oldFile.exists())
			oldFile.renameTo(new File((new StringBuilder()).append(filePath)
					.append(newFileName).append(
							oldFileName.substring(oldFileName.lastIndexOf("."),
									oldFileName.length())).toString()));
	}

	public Employee getEmp() {
		return emp;
	}

	public void setEmp(Employee emp) {
		this.emp = emp;
	}

	public List getEmpTypes() {
		return empTypes;
	}

	public void setEmpTypes(List empTypes) {
		this.empTypes = empTypes;
	}

	public List getLocations() {
		return locations;
	}

	public void setLocations(List locations) {
		this.locations = locations;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getCreateUser() {
		return createUser;
	}

	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	public String getEmpNo() {
		return empNo;
	}

	public void setEmpNo(String empNo) {
		this.empNo = empNo;
	}

	public String getOldEmpDistinctNo() {
		return oldEmpDistinctNo;
	}

	public void setOldEmpDistinctNo(String oldEmpDistinctNo) {
		this.oldEmpDistinctNo = oldEmpDistinctNo;
	}

	public String getConnectionType() {
		return connectionType;
	}

	public void setConnectionType(String connectionType) {
		this.connectionType = connectionType;
	}

	public String getConnectionNo() {
		return connectionNo;
	}

	public void setConnectionNo(String connectionNo) {
		this.connectionNo = connectionNo;
	}

	public List getBenefitTypes() {
		return benefitTypes;
	}

	public void setBenefitTypes(List benefitTypes) {
		this.benefitTypes = benefitTypes;
	}

	public String getExShiftEnable() {
		return exShiftEnable;
	}

	public void setExShiftEnable(String exShiftEnable) {
		this.exShiftEnable = exShiftEnable;
	}

	public String getApplierId() {
		return applierId;
	}

	public void setApplierId(String applierId) {
		this.applierId = applierId;
	}

	private static final long serialVersionUID = 0xc53a77b0ae03eebfL;
	SysConfigManager dbConfigManager;
	private Employee emp;
	private String connectionType;
	private String connectionNo;
	private String empMsn;
	private File file;
	private String fileContentType;
	private String fileFileName;
	private List locations;
	private List empTypes;
	private String applierId;
	private String createUser;
	private String empNo;
	private String oldEmpDistinctNo;
	private List benefitTypes;
	String exShiftEnable;
}
